<?php


namespace App\Service\Admin;


use App\Constants\ErrorCode;
use App\Constants\Model\CertificationCompanyApply;
use App\Dao\CertificationCompanyApplyDao;
use App\Dao\UserDao;
use App\Exception\BusinessException;
use App\Model\User;
use App\Utils\Log;
use App\Utils\Notice\Sender;
use App\Utils\Notice\UserCertificationCompanyAuditAllow;
use Hyperf\Database\Query\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;

class CertificationCompanyApplyService extends BaseService
{
    /**
     * @Inject()
     * @var CertificationCompanyApplyDao
     */
    protected $certificationCompanyApplyDao;

    /**
     * @Inject()
     * @var UserDao
     */
    protected $userDao;

    /**
     * @param array $where
     * @return array
     */
    public function index(array $where): array
    {
        $pageInfo = $this->extractPaginateInfo($where);
        $where = $this->formatWhereRegionToCooperative($where);
        $index = $this->certificationCompanyApplyDao->where($where)->with('user')->paginate(
            $pageInfo['perPage'], ['*'], 'page', $pageInfo['page']
        );
        return $this->formatIndex($index);
    }

    public function formatIndex(\Hyperf\Contract\LengthAwarePaginatorInterface $index)
    {
        $data = [];
        /** @var \App\Model\CertificationCompanyApply $certificationCompanyApply */
        foreach ($index->items() as $certificationCompanyApply) {
            $data[] = [
                'id' => $certificationCompanyApply->id,
                'user_avatar' => $certificationCompanyApply->user->avatar,
                'user_name' => $certificationCompanyApply->user->nickname,
                'user_phone' => $certificationCompanyApply->user->phone,
                'company_name' => $certificationCompanyApply->name,
                'credit_code' => $certificationCompanyApply->credit_code,
                'license_img' => $certificationCompanyApply->license_img,
                'message' => $certificationCompanyApply->message,
                'status' => $certificationCompanyApply->status,
                'created_at' => $certificationCompanyApply->user->created_at->toDatetimeString()
            ];
        }

        return [
            'data' => $data,
            'current_page' => $index->currentPage(),
            'total' => $index->total(),
            'per_page' => $index->perPage()
        ];
    }

    /**
     * @param int $certificationCompanyApplyId
     * @return \App\Model\CertificationCompanyApply
     * @throws \Exception
     */
    public function allow(int $certificationCompanyApplyId)
    {
        /** @var \App\Model\CertificationCompanyApply $certificationCompanyApply */
        $certificationCompanyApply = $this->certificationCompanyApplyDao->first(['id' => $certificationCompanyApplyId]);
        if (!$certificationCompanyApply) {
            throw new BusinessException(ErrorCode::CERTIFICATION_COMPANY_APPLY_NOT_FOUND);
        }
        if ($certificationCompanyApply->status != CertificationCompanyApply::STATUS_PENDING) {
            throw new BusinessException(ErrorCode::CERTIFICATION_COMPANY_APPLY_NOT_PENDING);
        }
        $certificationCompanyApply->status = CertificationCompanyApply::STATUS_ALLOW;

        /** @var User $user */
        $user = $this->userDao->first(['id' => $certificationCompanyApply->user_id]);

        $user->company_certification = \App\Constants\Model\User::COMPANY_CERTIFICATION_YES;

        Db::beginTransaction();
        try {
            $certificationCompanyApply->save();
            $user->save();
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollBack();
            Log::get()->error($exception->getMessage(), ['certification_company_apply_id' => $certificationCompanyApplyId]);
            throw $exception;
        }

        //发送企业信息审核通过通知
        Sender::send($certificationCompanyApply->user_id, new UserCertificationCompanyAuditAllow([]));
        return $certificationCompanyApply;
    }

    /**
     * @param int $certificationCompanyApplyId
     * @param array $data
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model|object
     */
    public function notAllow(int $certificationCompanyApplyId, array $data)
    {
        $certificationCompanyApply = $this->certificationCompanyApplyDao->first(['id' => $certificationCompanyApplyId]);
        if (!$certificationCompanyApply) {
            throw new BusinessException(ErrorCode::CERTIFICATION_COMPANY_APPLY_NOT_FOUND);
        }
        if ($certificationCompanyApply->status != CertificationCompanyApply::STATUS_PENDING) {
            throw new BusinessException(ErrorCode::CERTIFICATION_COMPANY_APPLY_NOT_PENDING);
        }
        $certificationCompanyApply->status = CertificationCompanyApply::STATUS_NOT_ALLOW;
        $certificationCompanyApply->fill($data);
        $certificationCompanyApply->save();

        //发送企业信息审核未通过通知
        Sender::send($certificationCompanyApply->user_id, new UserCertificationCompanyAuditAllow([]));
        return $certificationCompanyApply;
    }
}